<script>
	import commonApi from '@/api/common.js'
	import {
		mapState
	} from 'vuex';
	export default {
		computed: {
			...mapState(['locationWatch'])
		},
		watch: {
			// locationWatch(newVal) {
			// 	// console.log('Vuex locationWatch changed:', newVal, oldVal);
			// 	if (newVal) {
			// 		console.log('调用了app.vue获取位置信息')
			// 		this.startLocationWatch();
			// 	}
			// }
		},
		onLaunch() {
			this.startLocationWatch();
		},
		onShow() {
			
			// console.log('locationAllow',this.locationAllow)
			
		},
		onHide() {
			
		},
		data() {
			return {
				lastLatitude: null,
				lastLongitude: null
			}
		},
		methods: {
			startLocationWatch() {
				console.log('触发了startLocationWatch')
				if (this._locationStarted) return; // 防止多次启动
				this._locationStarted = true;
				// wx.startLocationUpdateBackground
				wx.startLocationUpdateBackground({
				  type: 'periodic',
				  desiredAccuracy: 'highest',
				  success: () => {
				    // ✅ 先主动获取一次当前位置
				    wx.getLocation({
				      type: 'gcj02', // 高德坐标，可根据需求修改
				      success: (res) => {
				        console.log('首次获取位置:', res.latitude, res.longitude);
				        this.lastLatitude = res.latitude;
				        this.lastLongitude = res.longitude;
				
				        if (this.$store.state.locationWatch) {
				          this.$store.commit('setLocation', {
				            latitude: res.latitude,
				            longitude: res.longitude
				          });
				          this.uploadLocationInfo(res.latitude, res.longitude);
				        }
				      },
				      fail: (err) => {
				        console.error('获取初始位置失败:', err);
				      }
				    });
				
				    // ✅ 后续监听位置变化
				    wx.onLocationChange((res) => {
				      if (
				        this.lastLatitude !== res.latitude ||
				        this.lastLongitude !== res.longitude
				      ) {
				        if (this.$store.state.locationWatch) {
				          console.log('位置变化:', res.latitude, res.longitude);
				          this.$store.commit('setLocation', {
				            latitude: res.latitude,
				            longitude: res.longitude
				          });
				          this.uploadLocationInfo(res.latitude, res.longitude);
				        }
				
				        this.lastLatitude = res.latitude;
				        this.lastLongitude = res.longitude;
				      }
				    });
				  },
				  fail: (err) => {
				    console.error('启动后台定位失败:', err);
				  }
				});

			},
			stopLocationWatch() {
				// this.$store.commit('setLocationWatch', false);
				// this.$store.commit('setLocationAllow', true);
				wx.offLocationChange();
				wx.stopLocationUpdate();
				this._locationStarted = false;
			},
			// 上传位置信息
			async uploadLocationInfo(latitude, longitude) {
				try {
					const params = {
						lat: latitude,
						lng: longitude
					};
					const result = await commonApi.uploadLocation(params)

					if (result.status == 200) {
						console.log('app.vue位置上传成功:', result)
						// this.getDispatchRoute()
					}
				} catch (error) {
					console.error('位置上传失败:', error)
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #F7F7F7;
		font-size: 28rpx;
		word-wrap: break-word;
		color: #2A2A2A;
	}

	@import "uview-ui/index.scss";
	@import "common/common.scss";
</style>